/**
 * 文件加密&解密 https://www.bilibili.com/video/BV1vs411n7TH?p=115
 */
#include <stdio.h>
#include "../Utils/FileIOUtils.h"

static char* FILE_READ_PATH = "../Read_Write_Test/test.txt";
static char* FILE_WRITE_PATH = "../Read_Write_Test/2.文件加密结果.txt";
static char* FILE_DECODE_PATH = "../Read_Write_Test/2.文件解密结果.txt";
static FILE *readFile, *writeFile;

void encode();
void decode();
void closeFile();

int main() {
    readFile = file_open_r(FILE_READ_PATH);
    writeFile = file_open_w(FILE_WRITE_PATH);
    //1.文件加密
    encode();
    //解密前, 先关闭文件
    closeFile();
    //2.解密文件
    decode();
    //关闭文件
    closeFile();
    return EXIT_SUCCESS;
}

//1.文件加密
void encode() {
    int c;
//    while (!file_eof(readFile)) {         //这种判断, 结尾有问题
//        c = file_getc(readFile);
    while ((c = file_getc(readFile)) != EOF) {
        c++;
        int c2 = file_putc(c, writeFile);   //将加密后的c写入文件
    }
    printf("加密完成: %s\n", FILE_WRITE_PATH);
}

//2.解密文件
void decode() {
    readFile = file_open_r(FILE_WRITE_PATH);
    writeFile = file_open_w(FILE_DECODE_PATH);
    printf("解密前:\n");
    int c;
//    while (!file_eof(readFile)) {         //这种判断, 结尾有问题
//        c = file_getc(readFile);
    while ((c = file_getc(readFile)) != EOF) {
        printf("%c", c);
        c--;
        int c2 = file_putc(c, writeFile);   //将解密后的c写入文件
    }
    printf("\n解密完成: %s\n", FILE_DECODE_PATH);
}

void closeFile() {
    file_close(readFile);
    file_close(writeFile);
}